package com.ax.center.service.impl;

import com.ax.center.dto.ApiResponse;
import com.ax.center.entity.Authority;
import com.ax.center.mapper.AuthorityMapper;
import com.ax.center.service.AuthorityService;
import com.ax.center.service.UserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zy
 * @date 2023/7/4 11:37
 */
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityMapper, Authority> implements AuthorityService {

    @Autowired
    private AuthorityMapper authorityMapper;

    @Autowired
    private UserAuthService userAuthService;

    @ApiOperation("查询权限表里所有的权限Id")
    @Override
    public ApiResponse queryAllAuthId() {
        List<Authority> authorities = authorityMapper.selectList(null);
        List<Long> list = authorities.stream().map(Authority::getId).collect(Collectors.toList());
        return ApiResponse.ok(list);
    }

    @ApiOperation("查询权限表里所有的权限信息")
    @Override
    public ApiResponse queryAllAuthInfo() {
        List<Authority> authorities = authorityMapper.selectList(null);
        return ApiResponse.ok(authorities);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse deleteById(Long id) {
        removeById(id);
        userAuthService.deleteByAuthId(id);
        return ApiResponse.ok("删除成功");
    }

    @Override
    public ApiResponse queryByPre() {
        List<Authority> authorities = authorityMapper.selectList(null);

        // 对权限进行分类
        List<Authority> queryPermissions = new ArrayList<>();
        List<Authority> deletePermissions = new ArrayList<>();
        List<Authority> updatePermissions = new ArrayList<>();
        List<Authority> addPermissions = new ArrayList<>();

        for (Authority permission : authorities) {
            String permissionName = permission.getAuthName();
            if (permissionName.startsWith("查询")) {
                queryPermissions.add(permission);
            } else if (permissionName.startsWith("删除")) {
                deletePermissions.add(permission);
            } else if (permissionName.startsWith("修改")) {
                updatePermissions.add(permission);
            } else if (permissionName.startsWith("新增")) {
                addPermissions.add(permission);
            }
        }
        // 构造结果
        List<List<Authority>> categorizedPermissions = new ArrayList<>();
        categorizedPermissions.add(queryPermissions);
        categorizedPermissions.add(deletePermissions);
        categorizedPermissions.add(updatePermissions);
        categorizedPermissions.add(addPermissions);
        return ApiResponse.ok(categorizedPermissions);
    }



}
